import {removeToken, setToken} from '@/util/auth'
import {getStore, setStore} from '@/util/store'
import {validatenull} from '@/util/validate'
import {deepClone} from '@/util/util'
import {getUserInfo, login} from "@/api/auth/login";
import {treeList} from "@/api/system/menu";
import {getButtons} from "@/api/auth/button";

function addPath(ele) {
    ele["icon"] = validatenull(ele["icon"]) ? 'icon-caidan' : ele["icon"];
    ele["meta"] = {keepAlive: ele.keepAlive}
    if (!(ele["children"] && ele["children"].length !== 0)) {
        ele["children"] = []
    } else {
        ele["children"].forEach(child => {
            addPath(child);
        })
    }
}

const user = {
    state: {
        userInfo: {},
        permission: {},
        roles: [],
        menuId: getStore({name: 'menuId'}) || [],
        menu: getStore({name: 'menu'}) || [],
        menuAll: getStore({name: 'menuAll'}) || [],
        token: getStore({name: 'token'}) || '',
    },
    actions: {
        //根据用户名登录
        LoginByUsername({commit}, userInfo) {
            return new Promise((resolve) => {
                login(userInfo).then(res => {
                    const data = res.data.data;
                    commit('SET_TOKEN', data.token);
                    commit('SET_INFO', data.info);
                    commit('DEL_ALL_TAG');
                    commit('CLEAR_LOCK');
                    resolve();
                })
            })
        },
        GetUserInfo({commit}) {
            return new Promise((resolve) => {
                getUserInfo().then(res => {
                    commit('SET_USERIFNO', res.data.data);
                    resolve();
                })
            })
        },
        // 登出
        LogOut({commit}) {
            return new Promise(() => {
                commit('SET_TOKEN', '')
                commit('SET_MENUID', {})
                commit('SET_MENUALL', []);
                commit('SET_MENU', [])
                commit('SET_TAG_LIST', [])
                commit('SET_ROLES', [])
                commit('DEL_ALL_TAG');
                commit('CLEAR_LOCK');
                removeToken()
            })
        },
        //注销session
        FedLogOut({commit}) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '')
                commit('SET_MENUID', {})
                commit('SET_MENUALL', []);
                commit('SET_MENU', [])
                commit('SET_TAG_LIST', [])
                commit('SET_ROLES', [])
                commit('DEL_ALL_TAG');
                commit('CLEAR_LOCK');
                removeToken()
                resolve()
            })
        },
        GetButtons({commit}) {
            return new Promise((resolve) => {
                getButtons().then(res => {
                    const data = res.data.data;
                    commit('SET_PERMISSION', data);
                    resolve();
                })
            })
        },
        //获取系统菜单
        GetMenu({commit, dispatch}) {
            return new Promise(resolve => {
                treeList().then((res) => {
                    const data = res.data.data
                    let menu = deepClone(data);
                    menu.forEach(ele => {
                        addPath(ele);
                    })
                    commit('SET_MENUALL', menu)
                    commit('SET_MENU', menu)
                    dispatch('GetButtons');
                    dispatch('GetUserInfo');
                    resolve(menu)
                })
            })
        },
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            setToken(token)
            state.token = token;
            setStore({name: 'token', content: state.token})
        },
        SET_INFO: (state, info) => {
            state.info = info;
            setStore({name: 'info', content: state.info})
        },
        SET_MENUID(state, menuId) {
            state.menuId = menuId;
            setStore({name: 'menuId', content: state.menuId, type: 'session'})
        },
        SET_USERIFNO: (state, userInfo) => {
            state.userInfo = userInfo;
            setStore({name: 'userInfo', content: state.userInfo})
        },
        SET_MENUALL: (state, menuAll) => {
            state.menuAll = menuAll
            setStore({name: 'menuAll', content: state.menuAll})
        },
        SET_MENU: (state, menu) => {
            state.menu = menu
            setStore({name: 'menu', content: state.menu})
            if (validatenull(menu)) return
            //合并动态路由去重
            let menuAll = state.menuAll;
            menuAll = menuAll.concat(menu).reverse();
            let newMenu = [];
            for (let item1 of menuAll) {
                let flag = true;
                for (let item2 of newMenu) {
                    if (item1.label == item2.label || item1.path == item2.path) {
                        flag = false;
                    }
                }
                if (flag) newMenu.push(item1);
            }
            state.menuAll = newMenu
            setStore({name: 'menuAll', content: state.menuAll, type: 'session'})
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles;
        },
        SET_PERMISSION: (state, permission) => {
            state.permission = {};

            permission.forEach(ele => {
                state.permission[ele.code] = true;
            });
            console.log(state.permission);
        }
    }

}
export default user
